import json
import sys
from pathlib import Path

from starlette.responses import JSONResponse

from app.utils.string_util import convert_json_values_to_str

# 获取项目根目录
root_dir = str(Path(__file__).resolve().parent.parent)
sys.path.append(root_dir)

from app.sql.mysql_main import main_opera

def insert_goods_brand(goods_brand) -> int:
    """
    插入新商品记录到数据库
    Returns:
        插入操作影响的行数
    Raises:
        DatabaseError: 数据库操作失败时抛出
    """
    try:
        # 2. 删除指定键
        # goods.pop("spec_list", None)  # 删除 spec_list 键
        json_str = json.dumps(goods_brand)  # 将字典转为字符串
        parsed_data = json.loads(json_str)  # 再将字符串解析为字典
        # 执行数据库操作
        # 1. 检查 goods_id 是否存在
        check_query = "SELECT 1 FROM goods_brand WHERE brand_id = %(brand_id)s"
        exists = main_opera(check_query, {"brand_id": parsed_data["brand_id"]}, True)
        if exists:
            # 2. 存在则执行 UPDATE
            update_query = """
            UPDATE goods_brand SET 
                brand_no = %(brand_no)s, 
                brand_name = %(brand_name)s, 
                remark = %(remark)s, 
                sales_rate_type = %(sales_rate_type)s, 
                sales_rate_cycle = %(sales_rate_cycle)s, 
                purchase_computing_cycle = %(purchase_computing_cycle)s, 
                purchase_computing_cycle1 = %(purchase_computing_cycle1)s, 
                sales_rate = %(sales_rate)s, 
                alarm_type = %(alarm_type)s, 
                alarm_days = %(alarm_days)s, 
                alarm_days1 = %(alarm_days1)s, 
                is_disabled = %(is_disabled)s, 
                modified = %(modified)s 
            WHERE brand_id = %(brand_id)s
           
            """
            result = main_opera(update_query, parsed_data, False)
            return result
        else:
            # 3. 不存在则执行 INSERT
            insert_query = """
             INSERT INTO fastapi.goods_brand 
                (brand_id, brand_no, brand_name, remark, sales_rate_type, 
                sales_rate_cycle, purchase_computing_cycle, purchase_computing_cycle1, 
                sales_rate, alarm_type, alarm_days, alarm_days1, is_disabled, modified, created)
                VALUES (%(brand_id)s, %(brand_no)s, %(brand_name)s, %(remark)s, %(sales_rate_type)s,
                           %(sales_rate_cycle)s, %(purchase_computing_cycle)s, %(purchase_computing_cycle1)s,
                           %(sales_rate)s, %(alarm_type)s, %(alarm_days)s, %(alarm_days1)s, %(is_disabled)s, %(modified)s, %(created)s)
            """
            result = main_opera(insert_query, parsed_data, False)
            return result
    except Exception as e:
        # 这里应该记录日志而不是简单打印
        print(f"Error inserting goods: {e}")
        raise
